package com.feiyisys.controller;

import com.feiyisys.bo.UpdateVideoStatusBO;
import com.feiyisys.common.PageResult;
import com.feiyisys.dto.FindVPageDTO;
import com.feiyisys.dto.UpdateVideoDTO;
import com.feiyisys.entity.Video;
import com.feiyisys.manager.AsyncVideoUploadManager;
import com.feiyisys.common.Result;
import com.feiyisys.service.VideoService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 文化遗产相关视频表 前端控制器
 * </p>
 *
 * @author wq
 * @since 2025-10-10
 */
@RestController
@RequestMapping("/video")
@Slf4j
@CrossOrigin("*")
public class VideoController {


    @Resource
    private VideoService videoService;

    @GetMapping("/list")
    public Result<Object> list() {
        return Result.success(videoService.list());
    }

    @GetMapping("/getVideoInfoById")
    public Result<Object> getVideoInfoById(@RequestParam("id") String id) {
        return Result.success(videoService.getVideoInfoById(id));
    }

    @PutMapping("/isUse")
    public Result<Object> updateIsUse(@RequestBody UpdateVideoStatusBO updateVideoStatusBO) {
        return Result.success(videoService.updateIsUse(updateVideoStatusBO));
    }

//    @PostMapping("/upload")
//    public Result<VodUploadResponse> uploadVideo(
//            @RequestParam(value = "videoFile") MultipartFile videoFile,
//            @RequestParam(value = "coverFile", required = false) MultipartFile coverFile,
//            @RequestParam(value = "title") String title,
//            @RequestParam(value = "description") String  description) {
//        VodUploadResponse vodUploadResponse = videoService.uploadVideo(videoFile, coverFile, title, description);
//        return Result.success(vodUploadResponse);
//    }

    /**
     * 异步上传接口
     */
    @PostMapping("/upload/async")
    public ResponseEntity<Map<String, Object>> asyncUploadVideo(
            @RequestParam("videoFile") MultipartFile videoFile,
            @RequestParam(value = "coverFile", required = false) MultipartFile coverFile,
            @RequestParam("title") String title,
            @RequestParam("description") String description) {

        try {
            String taskId = videoService.asyncUploadVideo(videoFile, coverFile, title, description);

            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("taskId", taskId);

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("提交异步上传任务失败", e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }

    /**
     * 查询上传任务状态
     */
    @GetMapping("/upload/status/{taskId}")
    public ResponseEntity<Map<String, Object>> getUploadStatus(@PathVariable String taskId) {
        try {
            AsyncVideoUploadManager.UploadTask task = videoService.getUploadTaskStatus(taskId);

            if (task == null) {
                Map<String, Object> result = new HashMap<>();
                result.put("success", false);
                result.put("message", "任务不存在");
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(result);
            }

            Map<String, Object> result = new HashMap<>();
            result.put("success", true);
            result.put("taskId", task.getTaskId());
            result.put("status", task.getStatus().name());
            result.put("progress", task.getProgress());
            result.put("fileName", task.getFileName());

            if (task.getStatus() == AsyncVideoUploadManager.UploadTask.UploadStatus.SUCCESS) {
                result.put("fileId", task.getFileId());
                result.put("mediaUrl", task.getMediaUrl());
                result.put("coverUrl", task.getCoverUrl());
            } else if (task.getStatus() == AsyncVideoUploadManager.UploadTask.UploadStatus.FAILED) {
                result.put("errorMessage", task.getErrorMessage());
            }

            return ResponseEntity.ok(result);

        } catch (Exception e) {
            log.error("查询上传状态失败: {}", taskId, e);
            Map<String, Object> result = new HashMap<>();
            result.put("success", false);
            result.put("message", e.getMessage());
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(result);
        }
    }


    @DeleteMapping("/delete/{id}")
    public Result<Object> delete(@PathVariable String id) {
        return videoService.removeById(id) ? Result.success("删除成功") : Result.error("删除失败");
    }

    @DeleteMapping("delete")
    public Result<Object> deletes(@RequestBody List<Long> vlist){
        return Result.success(videoService.removeByIds(vlist));
    }

    @PutMapping("update")
    public Result<Object> update(@RequestBody UpdateVideoDTO updateVideoDTO) {
        return videoService.updateVideo(updateVideoDTO) ? Result.success("更新成功") : Result.error("更新失败");
    }

    @PostMapping("findPage")
    public PageResult<Video> findPage(@RequestBody FindVPageDTO findVPageDTO){
        return PageResult.success(videoService.findPage(findVPageDTO));
    }


    /*
    获取浏览量为前六的视频
     */
    @GetMapping("getTop")
    public Result<List<Video>> getTop(){
        return Result.success(videoService.getTop());
    }


}
